package com.mtons.mblog.modules.template.directive;

import com.mtons.mblog.base.lang.Consts;
import com.mtons.mblog.base.utils.BeanMapUtils;
import com.mtons.mblog.modules.data.AnswerVO;
import com.mtons.mblog.modules.data.PostVO;
import com.mtons.mblog.modules.entity.Answer;
import com.mtons.mblog.modules.entity.Channel;
import com.mtons.mblog.modules.entity.Quest;
import com.mtons.mblog.modules.service.AnswerService;
import com.mtons.mblog.modules.service.QuestService;
import com.mtons.mblog.modules.template.DirectiveHandler;
import com.mtons.mblog.modules.template.TemplateDirective;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class AnswerContentsDirective extends TemplateDirective {
    @Autowired
    private AnswerService answerService;
    @Autowired
    private QuestService questService;

    @Override
    public String getName() {
        return "answerContents";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        Long questId = handler.getLong("questId", 0);
        String order = handler.getString("order", Consts.order.NEWEST);

        Set<Long> excludeQuestIds = new HashSet<>();

        if (questId <= 0) {
            List<Quest> quests = questService.findAll(Consts.STATUS_CLOSED);
            if (quests != null) {
                quests.forEach((q) -> excludeQuestIds.add(q.getId()));
            }
        }

        Pageable pageable = wrapPageable(handler, Sort.by(Sort.Direction.DESC, BeanMapUtils.postOrder(order)));
        Page<AnswerVO> result = answerService.paging(pageable, questId, excludeQuestIds);
        handler.put(RESULTS, result).render();
    }
}
